#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : 2024/9/20 17:26
# @Author  : Tom_zc
# @FileName: prepare-label.py
# @Software: PyCharm
import os
import sys
import logging

import click

BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.append(BASE_DIR)
sys.path.append(os.path.join(BASE_DIR, "utils"))
logging.basicConfig(level=logging.INFO,
                    format="%(asctime)s  %(levelname)s:%(message)s")

from utils.gitcode_helper import GitCodeHelper
from utils.parse_params import parse_repo_info_by_url
from utils.common import func_retry


class PrePareLabelHelper:

    def __init__(self, owner, repo, token):
        self.git_helper = GitCodeHelper(owner, repo, 0, token)

    @func_retry()
    def has_tag(self, branch, tag):
        info = self.git_helper.get_tag()
        names = [item['name'] for item in info]
        exists = tag in names
        if exists:
            logging.error("tag {} already".format(names))
            sys.exit(-1)

    @func_retry()
    def create_tag(self, branch, tag):
        self.git_helper.create_tag({"refs": branch, "tag_name": tag})


@click.command()
@click.option("--repo", help='tag')
@click.option("--branch", help='tag')
@click.option("--gitcode_token", help='tag')
@click.option("--tag", help='tag')
def main(tag, gitcode_token, repo, branch):
    token = gitcode_token
    url = repo
    owner, repo = parse_repo_info_by_url(url)
    branch = branch

    prepare_label_helper = PrePareLabelHelper(owner, repo, token)

    logging.info("create tag: {}".format(tag))
    prepare_label_helper.create_tag(branch, tag)


if __name__ == '__main__':
    main()
